<template>
    <div id="ConversationList">
      <div class="content-left">
        <!-- 搜索框 -->
        <div class="search"><search/></div>
        <p class="refresh">
          会话列表
          <el-tooltip effect="dark" placement="top" content="点击刷新列表">
            <el-button :loading="refreshIsLoading" @click="refreshConversationList">
              <i :class="{'el-icon-refresh':!refreshIsLoading}"/>
            </el-button>
          </el-tooltip>
        </p>
        <!-- 会话列表 -->
        <el-scrollbar  style="height: 95%">
          <div style="height: 520px">
            <conversation v-for="item in conversationList"
                          :conversation="item"
                          :key="item.conversationID"/>
          </div>
        </el-scrollbar>
      </div>
      <!-- 会话内容展示 -->
      <div v-if="isShowCurrentConversation" class="content-right">
        <!-- 头部 -->
        <div class="headline"> <h3>{{chatObjectName}}</h3>  </div>
        <!-- 主要 -->
        <div  v-if="" class="main">
          <el-scrollbar :native="false"
                        ref="myScrollbar" style="height: 100%">
            <div  style="height: 520px">
              <template v-if="isCompleted"><div class="unload">没有更多了</div></template>
              <template v-else>
                <el-button @click="loadMessage" ref="load" class="load"
                           :loading="loading" type="primary">
                  加载更多
                </el-button>
              </template>
              <conversation-message v-for="item in currentMessageList"
                                    :key="item.ID"
                                    @reeditMessage="reeditMessage"
                                    :image-list="getMessageListImage"
                                    :message="item"/>
              <div class="skip-bottom" @click="clickSkipBottom" v-show="isShowSkipBottom"> 回到底部 </div>
            </div>
          </el-scrollbar>
        </div>
        <!-- 底部 -->
        <div :style="bgColor" class="bottom">
          <!-- 功能按钮 -->
          <div class="function-btn">
            <ul class="left">
              <!-- 表情 -->
              <li>
                <el-popover placement="top" width="440"
                            v-model="emojiSelectVisible"
                            :offset="-180"
                            trigger="manual">
                    <el-tooltip  :open-delay="500"
                                 v-for="(item,index) in EMOJI"
                                 effect="dark"
                                 placement="top"
                                 :content="item.name">
                      <span @click="getClickEmoji(index)"
                            class="emoji"
                            :key="index">{{item.emoji}}</span>
                    </el-tooltip>
                  <svg-icon @focus="emojiSelectVisible=true"
                            @blur="emojiSelectVisible=false"
                            slot="reference" icon-class="function01"/>
                </el-popover>
              </li>
              <!-- 发送图片 -->
              <li>
                <svg-icon @click="handleSendImageClick" icon-class="function02"/>
                <input id="imagePicker"
                       ref="imagePicker"
                       @change="sendImage"
                       accept=".jpg,.jpeg,.png,.gif"
                       style="display: none"
                       type="file">
              </li>

              <!-- 发送视频 -->
              <li> <!-- 发送视频消息 -->
                <svg-icon @click="handleSendVideoClick" icon-class="function03"/>
                <!-- 上传视频 -->
                <input type="file"
                       id="videoPicker"
                       ref="videoPicker"
                       accept=".mp4"
                       @change="sendVideo"
                       style="display: none"/>
              </li>

              <!-- 发送文件 -->
              <li>
                <input ref="filePicker"
                       style="display:none;"
                       @change="sendFile"
                       type="file">
                <svg-icon @click="handleSendFileClick" icon-class="function04"/>
              </li>
            </ul>
            <ul class="right">
              <li>
                <svg-icon icon-class="function05"/>
              </li>
              <li>
                <svg-icon icon-class="function06"/>
              </li>
            </ul>
          </div>
          <!-- 文本输入框 -->
          <div class="text-box">
            <textarea @focus="bgColor={backgroundColor: '#ffffff'}"
                      @blur="bgColor=''"
                      ref="textarea"
                      @paste="pasteImage"
                      @keydown.enter.exact.prevent="sendTextMessage"
                      @keyup.ctrl.enter.prevent.exact="nextLine"
                      :style="bgColor"
                      v-model="content"
                      rows="6"/>
          </div>
          <el-tooltip class="item" effect="dark" content="按Ctrl+Enter发送消息" placement="left">
            <div @click="sendTextMessage" class="send"><i class="el-icon-s-promotion"/></div>
          </el-tooltip>
        </div>
      </div>
    </div>
</template>

<script>
  import Search from "@/views/chat/Search";
  import Conversation from "@/views/chat/Conversation";
  import ConversationMessage from "@/views/chat/ConversationMessage";
  import {mapGetters} from 'vuex'
  import EMOJI from "@/utils/emoji";
  import tim from "@/tim";
  import TIM from 'tim-js-sdk'

  export default {
    name: "ConversationList",
    components: {
      Search, Conversation, ConversationMessage
    },
    data() {
      return {
        EMOJI, // emoji 表情库
        emojiSelectVisible: false,//表情选择面板
        content: '', //消息内容
        bgColor: '',
        loading: false,
        action: process.env.VUE_APP_BASE_API,
        message: {},
        scrollLocation:0,
        isShowSkipBottom:false, // 回到底部按钮
        refreshIsLoading:false, // 刷新会话列表
      }
    },
    computed: {
      ...mapGetters([
        'id', 'friendList', 'conversationList',
        'currentConversation', 'conversationMessagesList',
        'toAccount','currentMessageList','isCompleted'
      ]),
      // 是否展示会话窗口
      isShowCurrentConversation(){
        if (this.currentConversation.conversationID) {
          return this.conversationList.filter(item => {
            return item.conversationID === this.currentConversation.conversationID
          })[0]
        } else {
          return false;
        }
      },
      // 聊天对象的名称
      chatObjectName(){
        // 获取聊天用户的昵称
        if(this.currentConversation.userProfile){
          return this.currentConversation.userProfile.nick
        }
        return ''
      },
      // 获取消息列表中的所有图片
      getMessageListImage(){
        let imageArray = []
        this.currentMessageList.forEach(item=>{
          // 判断消息类型为图片
          if(item.type === TIM.TYPES.MSG_IMAGE){
            imageArray.push(item.payload.imageInfoArray[0].url)
          }
        })
        return imageArray
      },
    },
    watch:{
      // 监听聊天消息列表
      'currentMessageList':function () {
        this.$nextTick(()=>{
          if(this.$refs.myScrollbar){
            // 将聊天列表滚动条移动至最后
            let scrollbar = this.$refs.myScrollbar.wrap;
            scrollbar.scrollTop = scrollbar.scrollHeight
          }
        })
      }
    },
    methods: {
      // 将用户点击的表情追加到文本框中
      getClickEmoji(index) {
        this.content += this.EMOJI[index].emoji
        console.log(this.EMOJI[index])
      },
      // 下一行
      nextLine(){
        this.content+='\n'
      },
      // 发送文本 消息
      sendTextMessage(){
        if(this.content.trim() === ''){
          this.content = ''
          this.$store.commit('chat/showMessage',{
            message:'不能发送空白消息哦！',
            type:'info'
          })
          return
        }
        console.log("发送文本消息")
        // 创建文本消息
        const message = tim.createTextMessage({
          to:this.toAccount,
          conversationType:this.currentConversation.type,
          payload:{text:this.content}
        })
        // 发送消息
        tim.sendMessage(message).then(()=>{
          console.log('文本消息发送成功！')
          this.$store.commit('chat/pushCurrentMessageList',message)
          this.content = ''
        }).catch(err=>{
          this.$store.commit('chat/showMessage',{
            message:err.message,
            type:'error'
          })
        })
      },
      // 点击发送视频消息
      handleSendVideoClick(){
        this.$refs.videoPicker.click()
      },
      // 点击发送图片消息
      handleSendImageClick(){
        this.$refs.imagePicker.click()
      },
      // 点击发送文件消息
      handleSendFileClick(){
        this.$refs.filePicker.click()
      },
      // 发送文件
      sendFile(){
        const message = tim.createFileMessage({
          to:this.toAccount,
          conversationType:this.currentConversation.type,
          payload:{
            file:this.$refs.filePicker
          },
          onProgress:(percent)=>{
            this.$set(message,'progress',percent)
          }
        })
        // 将文件消息存放到消息列表中
        this.$store.commit('chat/pushCurrentMessageList',message)
        // 发送文件消息
        tim.sendMessage(message).then(()=>{
          console.log("文件消息发送成功！")
          console.log(message)
          this.$refs.filePicker.value = ''
        }).catch(err=>{
          this.$store.commit('chat/showMessage',{
            message:err.message,
            type:'error'
          })
        })
      },
      // 发送图片
      sendImage(){
        // 创建图片消息
        const message = tim.createImageMessage({
          to:this.toAccount,
          conversationType:this.currentConversation.type,
          payload:{
            file:this.$refs.imagePicker
          },
          onProgress:(percent)=>{
            // 手动给message 实例加个响应式属性：progress
            this.$set(message,'progress',percent)
          }
        })
        // 将消息存放到聊天列表
        this.$store.commit('chat/pushCurrentMessageList', message)
        // 发送消息
        tim.sendMessage(message).then(()=>{
          console.log("图片消息发送成功！")
          console.log(message)
          this.$refs.imagePicker.value = ''
        }).catch(err=>{
          this.$store.commit('chat/showMessage',{
            message:err.message,
            type:'error'
          })
        })
      },
      // 发送视频
      sendVideo() {
        const message = tim.createVideoMessage({
          to:this.toAccount,
          conversationType:this.currentConversation.type,
          payload: {
            file: this.$refs.videoPicker
          },
          onProgress:(percent)=>{
            // 手动给message 实例加个响应式属性：progress
            this.$set(message,'progress',percent)
            console.log("file uploading :",percent)
          }
        })
        // 将消息存放入消息列表
        this.$store.commit('chat/pushCurrentMessageList', message)

        tim.sendMessage(message).then(()=>{
          console.log("视频消息发送成功")
          console.log(message)
          this.$refs.videoPicker.value =''
        }).catch(err=>{
          this.$store.commit('chat/showMessage',{
            message:err.message,
            type:'error'
          })
        })
      },
      // 粘贴图片获取并发送
      pasteImage(e){
        console.log("获取粘贴数据")
        let clipboardDate = e.clipboardData;
        let file;
        if (clipboardDate && clipboardDate.files && clipboardDate.files.length > 0) {
          // 获取剪贴板中的数据
          file = clipboardDate.files[0];
        }
        if(typeof file === 'undefined'){
          console.warn('file 是 undefined 请检查代码或浏览器兼容性！')
          return
        }
        // 创建图片消息
        const message = tim.createImageMessage({
          to:this.toAccount,
          conversationType:this.currentConversation.type,
          payload:{
            file:file
          },
          onProgress:(percent)=>{
            // 手动给message 实例加个响应式属性：progress
            this.$set(message,'progress',percent)
          }
        })
        // 将消息存放到聊天列表
        this.$store.commit('chat/pushCurrentMessageList', message)
        // 发送消息
        tim.sendMessage(message).then(()=>{
          console.log("图片消息发送成功！")
          console.log(message)
        }).catch(err=>{
          this.$store.commit('chat/showMessage',{
            message:err.message,
            type:'error'
          })
        })
      },

      // 加载消息
      loadMessage(){
        this.loading = true // 设置按钮的状态为加载中
        let scroll = this.$refs.myScrollbar.wrap;
        this.scrollLocation = scroll.scrollHeight - scroll.scrollTop
        // 加载消息
        this.$store.dispatch('chat/getMessageList',this.currentConversation.conversationID).then(()=>{
          this.loading = false
          scroll.scrollTop = scroll.scrollHeight - this.scrollLocation;
        })
      },
      // 处理滚动事件
      handleScroll() {
        if(this.$refs.myScrollbar){
          let scroll = this.$refs.myScrollbar.wrap;
          scroll.onscroll = () => {
            this.isShowSkipBottom = scroll.scrollHeight - scroll.scrollTop-735 > 100;
          }
        }
      },
      // 点击跳转至底部
      clickSkipBottom(){
        let scroll = this.$refs.myScrollbar.wrap;
        scroll.scrollTop = scroll.scrollHeight
        this.isShowSkipBottom = false
      },
      // 消息监听撤回消息重新编辑
      reeditMessage(content){
        console.log("将撤回的消息内容放到输入框")
        this.content += content
      },
      // 刷新会话列表
      refreshConversationList(){
        this.refreshIsLoading = true // 设置刷新按钮为加载中状态
        this.$store.dispatch('chat/getFriendList').then(()=>{
          console.log("刷新会话按钮：朋友列表刷新成功！")
        })
        this.$store.dispatch('chat/getConversationListTIM').then(()=>{
          setTimeout(()=>{
            this.$message.success("会话列表刷新成功！")
            this.refreshIsLoading = false
          },1500)
        })
      },
    },
    updated() {
      this.handleScroll()
    },
    mounted() {
      document.title = '聊天会话 💬'
    }
  };
</script>

<style>
  /* 隐藏el-scrollbar底部滚动条  */
  #ConversationList .el-scrollbar__wrap{overflow-x:hidden;}
</style>

<style scoped>
  .emoji{
    padding: 3px;
    font-size: 17px;
  }
  .emoji:hover{
    cursor: pointer;
    border: 1px solid #cdcdcd;
  }
</style>
<style lang="scss" scoped>
  #ConversationList {
    display: flex;
    width: 100%;
    height: 100%;
    background-color: #f2f3f5;
    /* 隐藏el-scrollbar底部滚动条  */
    .el-scrollbar__wrap{overflow-x:hidden;}
    .content-left{
      width: 28%;
      max-width: 300px;
      height: 100%;
      border-top: 1px solid transparent;
      border-right: 1px solid #eae8e8;
      background-color: #f6f6f6;
    }
    .search {
      margin: 14px 12px 10px;
    }
    .refresh{
      padding: 0 12px;
      margin: 0 0 4px;
      height: 24px;
      line-height: 24px;
      font-size: 12px;
      color: #99a2b9;
      .el-button{
        float: right;
        padding: 0;
        border: 0;
        line-height: 16px;
        background-color: transparent;
        font-size:20px;
        font-weight:700;
      }
    }
    .content-right{
      flex: 2;
      display: flex;
      flex-direction: column;
      border-left: 1px solid #e5e5e5;
      .headline{
        flex: 0.25;
        height: 40px;
        border-bottom: 1px solid #e5e5e5;
        h3{
          font-size: 20px;
          font-weight: 400;
          margin-left: 28px;
          line-height: 40px;
        }
      }
      .main {
        position: relative;
        flex: 2.8;
        height: 100%;
        border-bottom: 1px solid #e5e5e5;
        text-align: center;
        .skip-bottom{
          position: absolute;
          bottom: 2px;
          left: 50%;
          height: 26px;
          line-height: 26px;
          color: #0694f8;
          font-size: 12px;
          cursor: pointer;
        }
        .unload {
          margin-top: 8px;
          color: #a5b5c1;
          font-size: 12px;
        }
        .load {
          background-color: #f5f5f5;
          color: #20a0ff;
          border: 0;
          width:60px;
          height: 20px;
          padding: 8px 0 0;
          font-size: 12px;
        }
      }
      .bottom {
        flex: 0.6;
        position: relative;
        height: 100%;
        padding: 5px 20px 20px 20px;
        .function-btn {
          height: 30px;

          ul {
            padding: 0;
            margin: 0 0;
            list-style: none;

            li {
              cursor: pointer;
              font-size: 18px;
              color: #919191;
              margin-right: 12px;
              display: inline-block;
            }
          }

          .left {
            float: left;
          }

          .right {
            float: right;
          }
        }

        .text-box {
          height: 16%;

          textarea {
            background-color: #f5f5f5;
            width: 100%;
            outline: none;
            font-size: 14px;
            border: none;
            resize: none;
          }
        }
        .send {
          position: absolute;
          right: 20px;
          bottom: 22px;
          width: 32px;
          height: 25px;
          font-size: 25px;
          text-align: center;
          cursor: pointer;

          &:hover {
            color: #20a0ff;
          }
        }
      }
    }
  }
</style>
